import Taro, { Component, Config } from '@tarojs/taro'
import { Image, ScrollView, Text, View } from '@tarojs/components'
import classNames from 'classnames'
import './index.scss'
import moment from "@/assets/js/moment.min"
import { getPage } from "@/api/productApi"
import { getCustomPage } from "@/api/pageApi"
import { toAnyPage, toSearchPage, toSeckillListPage } from "@/utils/page_router"
import { getSharePath, getActivityTimeStorage, setActivityTimeStorage } from '@/utils/storage'
import { APP_NAME, TAB_BAR_HEIGHT, NAV_BAR_HEIGHT } from '@/config/config'
import { TabBar, Loading, Version, LoadMore } from '@/components/index'
import ActivityGoods from "@/components/activity/goods/index"
// import ActivityCoupon from "@/components/activity/coupon/index"
import NewsOne from "@/components/custom-layout/news-one"
import NavGroupTwo from "@/components/custom-layout/nav-group-two"
import CarouselTwo from "@/components/custom-layout/carousel-two"
import GoodsOne from "@/components/custom-layout/goods-one"
import GoodsTwo from "@/components/custom-layout/goods-two"
import GoodsThree from "@/components/custom-layout/goods-three"
import GoodsFour from "@/components/custom-layout/goods-four"
import GoodsFive from "@/components/custom-layout/goods-five"
import GoodsSix from "@/components/custom-layout/goods-six"
import GoodsSeven from "@/components/custom-layout/goods-seven"
import GoodsEight from "@/components/custom-layout/goods-eight"
import GoodsNine from "@/components/custom-layout/goods-nine"
import GoodsTen from "@/components/custom-layout/goods-ten"
import GridImg from "@/components/custom-layout/grid-img"
import BlankSpace from "@/components/custom-layout/blank-space"
import AuxiliaryLine from "@/components/custom-layout/auxiliary-line"

const defTabKey = 'recommend'
let CAROUSEL_HEIGHT = 0
// const TAB_NAV_HEIGHT = 72
// const { capsule } = APP_SYSTEM_INFO
export default class Index extends Component {
  state: any
  navBar: any
  tabNav: any
  pageConfig: any
  activityInfo: any
  config: Config = {
    navigationStyle: 'custom',
    backgroundTextStyle: "dark",
    enablePullDownRefresh: true,
  }

  constructor() {
    super(...arguments)
    this.state = {
      tabKey: defTabKey,
      loading: true,
      customList: [],
      page: 1,
      limit: 10,
      goodsList: [],
      loadStatus: 'loading',
      showActivity: false,
    }
    this.pageConfig = {}
  }

  componentDidMount () {
    this.getIndexData()
  }

  //  下拉刷新
  onPullDownRefresh() {
    const { tabKey } = this.state
    if (tabKey === defTabKey) {
      this.getIndexData()
    } else {
      this.setState({
        page: 1,
        goodsList: [],
        loadStatus: 'loading'
      }, () => {
        this.getGoods()
      })
    }
  }

  //  上拉加载
  onReachBottom() {
    this.getGoods()
  }

  //  分享小程序
  onShareAppMessage() {
    return { title: APP_NAME, path: getSharePath() }
  }

  //  获取首页数据
  getIndexData () {
    const { params } = this.$router
    getCustomPage(params.key).then(({ data, timestamp }) => {
      const list = (data.content || []).map(item => {
        switch (item.key) {
          case 'navGroup':
            const { list=[], colNumber=5, rowNumber=2 } = item
            //  乘积
            const product = colNumber * rowNumber
            const num = Math.ceil(list.length / product)
            const arr:any = []
            for (let i=0; i<num; i++) {
              arr.push([])
            }
            for (let i=0; i<list.length; i++) {
              arr[Math.floor(i / product)].push(list[i])
            }

            item.list = arr
            break
          case 'carousel':
            CAROUSEL_HEIGHT = item.height
            break
          case 'navBar':
            this.navBar = item
            break
          case 'tabNav':
            this.tabNav = item
            break
          case 'pageConfig':
            this.pageConfig = item
            break
          case 'activityGoods':
            this.activityInfo = item
            break
        }
        return item
      })
      this.setState({
        customList: list
      }, () => {
        this.setState({
          loading: false
        })
        Taro.stopPullDownRefresh()
      })

      this.activityInfo && setTimeout(() => {
        this.showActivity(timestamp, this.activityInfo)
      }, 3000)
    })
  }

  //  显示活动
  showActivity(time: number, goods: any) {
    const item = getActivityTimeStorage(goods.id)
    if (!item || item && moment(time).isAfter(item['time'])) {
      setActivityTimeStorage(goods.id, {
        id: goods.id,
        type: 'goods',
        time: time + 86400000
      })
      this.setState({
        showActivity: true,
      })
    }
  }

  //  关闭活动
  closeActivity() {
    this.setState({
      showActivity: false,
    })
  }

  //  分页获取商品
  getGoods() {
    const { page, limit, tabKey, goodsList, loadStatus }:any = this.state
    const query = {}
    if (loadStatus === 'noMore') {
      return
    }

    if (tabKey !== defTabKey) {
      query['categoryId'] = tabKey
    }

    getPage({ page, limit, ...query }).then(res => {
      const { list, totalCount } = res.data
      this.setState({
        page: page + 1,
        goodsList: page === 1 ? list : goodsList.concat(list),
        loadStatus: (page * limit >= totalCount) ? 'noMore' : 'loading',
      }, () => {
        Taro.stopPullDownRefresh()
      })
    })
  }

  //  切换tab
  onSwitchTab(key) {
    this.setState({
      page: 1,
      tabKey: key,
      goodsList: [],
      loadStatus: 'loading'
    }, () => {
      this.getGoods()
    })
  }

  render () {
    const { tabNav, pageConfig, activityInfo } = this
    const { customList, tabKey, loading, goodsList, loadStatus, showActivity } = this.state
    {/*// @ts-ignore*/}
    return (<View className='index custom-page' style={{ '--page-bg-img': `url(${pageConfig.bgImg})` }}>
      {loading && <Loading isCover/>}
      {/* 顶部导航栏 */}
      {/*{pageConfig.showNavBar && navBar && <View className='fy-popup fy-popup--top nav-bar' style={{ height: `${NAV_BAR_HEIGHT}px`, backgroundPosition: `left 50% bottom -${CAROUSEL_HEIGHT + TAB_NAV_HEIGHT}rpx` }}>*/}
      {/*    <View className='nav-bar__area d-f a-i-c' style={{ width: `${capsule.left}px`, height: `${capsule.height}px`, top: `${capsule.top}px` }}>*/}
      {/*      {navBar.img && <Image src={navBar.img} className='nav-bar__logo'/>}*/}
      {/*        <View className='nav-bar__input d-f a-i-c' onClick={() => toSearchPage()}>*/}
      {/*            <View className='input-prefix bnn-icon m-r-10'>&#xe65c;</View>*/}
      {/*            <View className='input-placeholder'>{navBar.placeholder}</View>*/}
      {/*        </View>*/}
      {/*    </View>*/}
      {/*</View>}*/}
      {/* 顶部选项卡导航 */}
      {pageConfig.showTabNav && tabNav && <View className='tab-nav' style={{
        top: `${pageConfig.showNavBar ? NAV_BAR_HEIGHT : 0}px`,
        color: tabNav.color,
        backgroundPosition: `left 50% bottom -${CAROUSEL_HEIGHT}rpx`
      }}>
          <View className={classNames('tab-nav__left tab-nav__cty-item', {['tab-nav__cty-active']: tabKey === defTabKey})} onClick={this.onSwitchTab.bind(this, defTabKey)}>
              <Text className='tab-nav__cty-text'>精选</Text>
          </View>
        {/*// @ts-ignore*/}
          <ScrollView scrollX enhanced showScrollbar={false} className='tab-nav__cty-scroll'>
              <View className='tab-nav__cty-list'>
                {tabNav.list.map(cty => {
                  return (<View key={cty.id} className={classNames('tab-nav__cty-item', {['tab-nav__cty-active']: tabKey === cty.id})} onClick={this.onSwitchTab.bind(this, cty.id)}>
                    {cty.img ? (
                      <Image src={cty.img} mode='heightFix' className='tab-nav__cty-img'/>
                    ) : (
                      <Text className='tab-nav__cty-text'>{cty.name}</Text>
                    )}
                  </View>)
                })}
              </View>
          </ScrollView>
          <View className='tab-nav__right' onClick={() => toSearchPage()}>全部</View>
      </View>}

      <View className='index-custom' style={{ display: tabKey === defTabKey ? 'block' : 'none' }}>
        <View className='index-custom__bg' style={{ paddingBottom: `${CAROUSEL_HEIGHT}rpx` }}/>
        {customList.map((item, k) => {
          const { marginTop=0, pageMargin=0 } = item
          return (<View key={k} className='custom-it-em'>
            {
              {
                'carousel': <CarouselTwo { ...item }/>,         // 轮播图
                'navGroup': <NavGroupTwo { ...item }/>,         // 导航组
                'newPeopleExclusive': <GoodsEight { ...item }/>,// 新人专享
                'fightGroups': <GoodsNine { ...item }/>,        // 拼团商品
                'newsService': <NewsOne { ...item }/>,          // 新闻播报
                'gridImg': <GridImg { ...item }/>,              // 栅格图片

                //  工具组件
                'blankSpace': <BlankSpace { ...item }/>,        // 新闻播报
                'auxiliaryLine': <AuxiliaryLine { ...item }/>,  // 栅格图片
              }[item.key]
            }

            {/* 商品列表模板1 */}
            {item.key === 'seckill' && <View className='goods-wrap goods-wrap__one' style={{ marginTop: `${marginTop}rpx` }}>
              {item.title && <View className='goods-wrap__head d-f a-i-b j-c-b' style={{ padding: `0 ${pageMargin}rpx` }}>
                <View className='goods-wrap__title'>{item.title}</View>
                <View className='goods-wrap__more d-f a-i-c' onClick={() => toSeckillListPage()}>
                  更多<View className='bnn-icon'>&#xe866;</View>
                </View>
              </View>}
                <View className='goods-wrap__body'>
                  <GoodsTen { ...item } marginTop={pageMargin}/>
                </View>
            </View>}

            {/* 商品列表模板1 */}
            {item.key === 'goodsList' && [2, 3, 4, 5, 6, 7].indexOf(Number(item.showMod)) >= 0 && <View className='goods-wrap goods-wrap__one' style={{ marginTop: `${marginTop}rpx` }}>
              {item.title && <View className='goods-wrap__head d-f a-i-b j-c-b' style={{ padding: `0 ${pageMargin}rpx` }}>
                  <View className='goods-wrap__title'>{item.title}</View>
                  <View className='goods-wrap__more d-f a-i-c' onClick={() => toAnyPage(item.moreUrl)}>
                    {item.moreName}
                      <View className='bnn-icon'>&#xe866;</View>
                  </View>
              </View>}
              {item.coverImg && <View className='goods-wrap__cover-img d-f' style={{ padding: `0 ${pageMargin}rpx`, marginTop: `${pageMargin}rpx` }}>
                  <Image mode="widthFix" src={item.coverImg} onClick={() => toAnyPage(item.coverUrl)}/>
              </View>}
                <View className='goods-wrap__body'>
                  {
                    {
                      2: <GoodsTwo { ...item } marginTop={pageMargin}/>,
                      3: <GoodsThree { ...item } marginTop={pageMargin}/>,
                      4: <GoodsFour { ...item }/>,
                      5: <GoodsFive { ...item }/>,
                      6: <GoodsSix { ...item } marginTop={pageMargin}/>,
                      7: <GoodsSeven { ...item } marginTop={pageMargin}/>,
                    }[item.showMod]
                  }
                </View>
            </View>}

            {/* 商品列表模板2 */}
            {item.key === 'goodsList' && [1].indexOf(Number(item.showMod)) >= 0 && <View className='goods-wrap goods-wrap__two'>
              {item.coverImg && <Image mode="widthFix" src={item.coverImg} className='goods-wrap__cover-img' onClick={() => toAnyPage(item.coverUrl)}/>}
                <View className='goods-wrap__box' style={{ margin: `${item.imgMarginTop}rpx ${item.pageMargin}rpx 0 ${item.pageMargin}rpx` }}>
                  {item.title && <View className='goods-wrap__head d-f a-i-b j-c-b'>
                      <View className='goods-wrap__title'>{item.title}</View>
                      <View className='goods-wrap__more d-f a-i-c' onClick={() => toAnyPage(item.moreUrl)}>
                        {item.moreName}
                          <View className='bnn-icon'>&#xe866;</View>
                      </View>
                  </View>}
                    <View className='goods-wrap__body'>
                      {/* 商品列表 */}
                      {item.showMod === 1 && <GoodsOne { ...item }/>}
                    </View>
                </View>
            </View>}
          </View>)
        })}
        <Version/>
      </View>

      <View className='index-category' style={{ display: tabKey !== defTabKey ? 'block' : 'none' }}>
        <GoodsTwo id={`goods-list`} list={goodsList} pageMargin={30} marginTop={30}/>
        <LoadMore status={loadStatus}/>
        {loadStatus === 'noMore' && <Version/>}
      </View>

      <ActivityGoods isOpened={showActivity} info={activityInfo} onClose={this.closeActivity.bind(this)}/>
      {/*<ActivityCoupon isOpened={showActivity} info={activityInfo} onClose={this.closeActivity.bind(this)}/>*/}

      <View style={{height: `${TAB_BAR_HEIGHT}px`}}/>
      <TabBar />
    </View>)
  }
}
